/*
 * @Author: wwssaabb
 * @Date: 2021-07-03 10:22:45
 * @LastEditTime: 2021-07-05 10:14:36
 * @FilePath: \demo\koa2_demo\demo\连mongodb接数据库增删改查_demo\app.js
 */

const koa = require('koa')
const router = require('koa-router')()
const bodyParser = require('koa-bodyparser')

const app = new koa()
app.use(bodyParser())
app.use(async (ctx,next)=>{
  ctx.set('Access-Control-Allow-Origin','*')
  ctx.set('Access-Control-Allow-Methods','OPTIONS,GET,POST,PUT,DELETE')
  await next()
})

require('./mongodb/index.js')   //mongodb数据库连接，test数据库
const User=require('./mongodb/model/user.js')   //获取user集合操作对象

router.get('/',(ctx,next)=>{
  ctx.status=301
  ctx.redirect('/list')
})

router.get('/index',(ctx,next)=>{
  ctx.status=301
  ctx.redirect('/list')
})

router.get('/list',async (ctx,next)=>{
  ctx.status=200
  const list= await User.find()
  console.log(list)
  ctx.body=list
})

router.get('/getInfo',async (ctx,next)=>{
  let id=ctx.request.query._id
  ctx.status=200
  const info= await User.findOne({_id:id})
  console.log(info)
  ctx.body=info
})

router.post('/add',async (ctx,next)=>{
  let obj=ctx.request.body
  await User.create(obj).then(res=>{
    console.log(res)
    ctx.status=200
    ctx.body={statusCode:200,message:'添加用户成功'}
  }).catch(err=>ctx.body=err)
})

router.post('/modify',async (ctx,next)=>{
  let obj=ctx.request.body
  let _id=obj._id
  await User.updateOne({_id:_id},obj).then(res=>{
    console.log(res)
    ctx.status=200
    ctx.body={statusCode:200,message:'修改成功'}
  }).catch(err=>ctx.body=err)
})

router.post('/delete',async (ctx,next)=>{
  let obj=ctx.request.body
  await User.findOneAndDelete(obj).then(res=>{
    console.log(res)
    ctx.status=200
    ctx.body={statusCode:200,message:'删除用户成功'}
  }).catch(err=>ctx.body=err)
})

app.use(router.routes())
app.use(router.allowedMethods())
app.listen(3000,err=>{
  if(!err){
    console.log('服务器开启成功！')
  }else{
    console.log(err)
  }
  
})